<template>
  <div class="chatRoom">
    <div class="msgList-area">
      <!-- prettier-ignore -->
      <ul class="list" ref="msgBox">
        <li v-for="item in list" :key="item.key" class="item">
          <template v-if="item.type == 'login'">
            <!-- prettier-ignore -->
            <span class="dis-ib name">
              <!-- 欢迎<span class="text-blue">{{ item.name }}</span>进入直播间 -->
               {{ item.content }}
            </span>
          </template>
          <template v-else>
            <span :class="{ 'dis-ib name': true, 'text-blue': item.isMe }">
              {{ item.isMe ? item.name : item.name.replace(/.{4}$/,'****') }}：
            </span>
            <span class="content" v-if="item.msgType==0">{{ item.content }}</span>
            <span class="content" v-if="item.msgType==1">
              <img class="img" :src="item.content">
            </span>
          </template>
        </li>
      </ul>
      <button
        type="button"
        class="btn btnSign"
        v-if="isShowBtnSign"
        @click="sengSign()"
      >
        <img class="img-inline" :src="btnSign" />
      </button>
    </div>
    <div class="input-area">
      <el-input
        type="textarea"
        class="input-msg"
        :rows="2"
        :autosize="{ minRows: 2, maxRows: 2 }"
        placeholder="请输入文字"
        resize="none"
        v-model="uMessage"
      >
      </el-input>
    </div>
    <div class="ctrl-area">
      <el-button type="primary" size="small" @click="sendMsg(true)"
        >发送</el-button
      >
    </div>
  </div>
</template>

<script>
import { bus } from '@/bus.js';
import { mapState, mapMutations } from 'vuex';
import { emoji } from '@/assets/emoji/emoji.js';
let btnSign = require('@/assets/cta_sign in.png');
let btnEmot = require('@/assets/28_emoticon.png');
let btnKB = require('@/assets/28_keyboard.png');
import { dateFormat } from '../assets/dataFormat';
import storage from '@/assets/storage.js';

export default {
  name: 'ChatByCus',
  mixins: [],
  props: {},
  data() {
    return {
      isDev: process.env.NODE_ENV === 'development',
      isShowBtnSign: true,
      btnSign,
      btnEmot,
      btnKB,
      emoji,
      roomInfo: {
        eSCompanyId: '',
        unionId: '',
        roomId: '',
      },
      uMsgType: 0, //0：文字，1：图片
      uMessage: '',
      max: 200,
      isFirstLogin: false,
      userId: '', //从登陆后缓存的localStorage中获取，详见 userInRoom 方法
      wsToken: null,
      zanHtml: '',
      heightFooter: '20vw',
      list: [{ type: 'login', content: '欢迎来到直播间，文明发言，理性讨论' }],
    };
  },
  computed: {
    ...mapState(['objRoom']),
  },
  watch: {},
  methods: {
    ...mapMutations([]),
    formatMsg: function(msg) {
      return {
        isMe: this._.get(msg, 'nickName') == this.userId,
        unionId: this._.get(msg, 'unionId', ''),
        eSCompanyId: this._.get(msg, 'eSCompanyId', ''),
        externalUserid: this._.get(msg, 'externalUserid', ''),
        name: this._.get(msg, 'nickName', this.userId),
        msgType: this._.get(msg, 'msgType', ''),
        content: this._.get(msg, 'msgBody', ''),
      };
    },
    userInRoom(token) {
      let userName = storage.getLS('userName') + '';
      this.$set(this, 'userId', userName);
      let params = {
        token: token,
        roomId: this._.get(this.$route, 'query.roomId'),
      };
      return this.$api
        .进入房间(params, {})
        .then((res) => {
          if (res.code === 200) {
            return Promise.resolve(res.data);
          } else {
            return Promise.reject(res);
          }
        })
        .then((res) => {
          this.$set(this.roomInfo, 'title', res.roomName);
          document.title = res.roomName;
          this.$set(this.roomInfo, 'cover', res.roomBgImg);
          this.$set(this.roomInfo, 'm3u8Stream', res.videoLiveUrl);
          // bus.$emit('获得推流地址', res);
          if (this.isFirstLogin) {
            this.list.push({ type: 'login', name: userName });
            this.isFirstLogin = false;
          }
        })
        .catch((err) => {
          // this.$toasted.show('ws身份认证失败');
        })
        .finally(() => {});
    },
    switchMsgType: function(uMsgType) {
      if (uMsgType == 1) {
        this.uMessage = '';
      }
      this.uMsgType = uMsgType;
      this.resetHeightFooter();
    },
    sengSign: function() {
      let parsma = { token: this.wsToken };
      let msg = Object.assign(
        {
          tcpCode: 3,
          reviewState: 1, //0:未审核 1:通过 2:拦截
          msgType: 0,
          msgBody: '签到',
          addTime: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        },
        this.roomInfo
      );

      this.$api
        .直播间发送消息(parsma, msg)
        .then((res) => {
          this.isShowBtnSign = false;
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          // this.pushList(msg);
        });
    },
    sendMsg: _.throttle(
      function(msgObj) {
        let parsma = { token: this.wsToken };
        let msg = Object.assign(
          {
            tcpCode: 3,
            reviewState: this.uMsgType == 0 ? 0 : 1, //0:未审核 1:通过 2:拦截
            msgType: this.uMsgType,
            msgBody: this.uMessage,
            addTime: dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
          },
          msgObj,
          this.roomInfo
        );

        this.$api
          .直播间发送消息(parsma, msg)
          .then((res) => {
            if (res.code == 400) {
              bus.$emit('token验证失败');
            }
          })
          .catch((err) => {
            console.error(err);
          })
          .finally(() => {
            // this.pushList(msg);
          });
        this.uMessage = '';
      },
      1000,
      { trailing: false }
    ),
    sendZan: function() {
      let parsma = { token: this.wsToken };
      this.zan();
      let msg = Object.assign(
        {
          tcpCode: 5,
          msgType: 0,
        },
        this.roomInfo
      );
      this.$api
        .直播间点赞(parsma, msg)
        .then((res) => {})
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {});
    },
    zan: function() {
      this.zanHtml = new Array(1).fill(1).reduce((t, v, i, a) => {
        t += `<i class="fa fa-heart parentImg parentImg${i}"></i>`;
        return t;
      }, '');
      setTimeout(() => {
        this.zanHtml = '';
      }, 1000 * 2);
    },
    toBottom: function() {
      if (this._.isUndefined(this.$refs.msgBox)) return;
      this.$nextTick(() => {
        if (this._.isUndefined(this.$refs.msgBox)) return;
        this.$refs.msgBox.scrollTop = this.$refs.msgBox.scrollHeight;
      });
    },
    pushList: function(msg) {
      let item = this.formatMsg(msg);
      this.list.push(item);
      if (this.list.length > this.max) {
        this.list.shift();
      }
      if (this._.isUndefined(this.$refs.msgBox)) return;
      this.toBottom();
    },
  },
  mounted() {
    this.$set(
      this.roomInfo,
      'eSCompanyId',
      this._.get(this.$route.query, 'escompanyid')
    );
    this.$set(
      this.roomInfo,
      'unionId',
      this._.get(this.$route.query, 'unionid')
    );
    this.$set(this.roomInfo, 'roomId', this._.get(this.$route.query, 'roomId'));
    bus.$on('ws身份认证成功', (wsMsg) => {
      this.$set(this, 'wsToken', wsMsg.token);
      this.userInRoom(wsMsg.token);
    });
    bus.$on('某个用户发言', (msg) => {
      this.pushList(msg);
    });
  },
};
</script>

<style scoped lang="less" src="./cbcPC.less"></style>
